package edu.qd.learn.newchapter.chapter03.reflect.demo01.dao;

import edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.BeanInfo;
import edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.BeanResult;
import lombok.Getter;

import java.util.Vector;

/**
 * 一个用来管理和实例化类的工厂模式
 */
public class BeanFactoryCopy {

    @Getter
    private static Vector<BeanResult> pool = new Vector<>();


    /**
     * 异常处理
     *
     * @param bean 类信息
     */
    private static void checkArgs(BeanInfo bean) {
        if (bean.getBeanName() == null || bean.getBeanName().isEmpty()) {
            throw new RuntimeException("对不起，请正确传入实例别名");
        }
        if (bean.getBeanPath() == null || bean.getBeanPath().isEmpty()) {
            throw new RuntimeException("对不起，请正确传入实例路径");
        }
    }

    private static Object createObject(String classPath) {
        try {
            Class<?> aClass = Class.forName(classPath);

            Object o = aClass.newInstance();
            return o;
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param beans 用来存储大量待实例化的类信息
     */
    public static void createClassInstance(BeanInfo... beans) {
        for (BeanInfo bean : beans) {
            checkArgs(bean);
            BeanResult br = new BeanResult();
            br.setBeanName(bean.getBeanName());
            br.setBeanInstance(createObject(bean.getBeanPath()));
            putBeanResultIntoPool(br);
        }
    }

    /**
     * 把生成的实例化 后的beanresult存储到池里面
     *
     * @param br 实例化以后的类的信息对象
     */
    public static void putBeanResultIntoPool(BeanResult br) {
        pool.add(br);
    }

    public static void main(String[] args) {
        BeanInfo bi = new BeanInfo("dog", "edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.Dog");
        BeanInfo bi1 = new BeanInfo("dog1", "edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.Dog");
        BeanFactory.createClassInstance(bi,bi1);


        System.out.println(BeanFactory.getPool());
    }

}